package com.lry.netty01.server.queue;

import com.lry.netty01.server.Server;
import com.lry.netty01.server.entity.FixedFrame;
import com.lry.netty01.server.entity.Packet;
import com.lry.netty01.server.processor.RequestProcessor;
import com.lry.netty01.server.utils.ChannelUtil;
import com.lry.netty01.server.utils.CommandUtil;

import java.util.LinkedList;
import java.util.Queue;

public class Task implements Runnable{

        private Packet packet;


        public Task(Packet packet){
            this.packet = packet;
        }

        @Override
        public void run() {
            boolean isUp = packet.isUp;
            FixedFrame request = packet.request;
            //客户端发给服务端的报文, 注册，心跳，报警
            if(isUp){
                RequestProcessor firstRequestProcessor = Server.getFirstRequestProcessor();
                firstRequestProcessor.processRequest(packet.channel,request);
            }
            //服务器下发给客户端的报文，操作/心跳/查询报文
            else{
                if(request.getCmd()!= CommandUtil.HEART_BEAT_CMD){
                    Queue<Packet> pendingQueue = ChannelUtil.PENDING_MAP.get(request.getDevId());
                    if(null==pendingQueue){
                        pendingQueue = new LinkedList<>();
                    }
                    pendingQueue.add(packet);
                    ChannelUtil.PENDING_MAP.put(request.getDevId(),pendingQueue);
                }

                packet.channel.writeAndFlush(request);
            }


        }

    }